//
//  TodayViewController.m
//  ClassWidget
//
//  Created by Zinzie on 14-9-16.
//  Copyright (c) 2014年 Zinzie. All rights reserved.
//

#import "TodayViewController.h"
#import <NotificationCenter/NotificationCenter.h>
@interface TodayViewController () <NCWidgetProviding>{
    int weekday;
    int weekCount;
}

@property (weak, nonatomic) IBOutlet UIView *classView;
@property (strong, nonatomic) IBOutlet UIView *widgetView;
@property (nonatomic,strong) NSMutableArray *displayArray;
@end

@implementation TodayViewController

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(userDefaultsDidChange:)
                                                     name:NSUserDefaultsDidChangeNotification
                                                   object:nil];
    }
    return self;
}

-(int )getWeekday{
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitWeekday;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:date];
    
    return [dateComponent weekday]-1;
}

-(int)getWeekCount{
    NSDate *date = [NSDate date];
    NSDateComponents *termStartDate  = [[NSDateComponents alloc] init];
    [termStartDate setDay:7];
    [termStartDate setMonth:9];
    [termStartDate setYear:2015];
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *StartDate = [gregorian dateFromComponents:termStartDate];
    int initunitFlags = NSCalendarUnitDay | NSCalendarUnitWeekday;
    NSDateComponents *resultComps = [gregorian components:initunitFlags fromDate:StartDate  toDate:date  options:0];
    
    return [resultComps day]/7+1;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.preferredContentSize = CGSizeMake(320, 65);
    self.classView.hidden  = YES;
    [self.view viewWithTag:92].hidden = YES;
    self.displayArray = [[NSMutableArray alloc]init];
    NSLog(@"hereasasdafclass");
    [self updateClassInfo];
    [self.view viewWithTag:97].hidden = YES;

    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated{
    [self updateClassInfo];
    [super viewWillAppear:animated];
}


- (void)userDefaultsDidChange:(NSNotification *)notification {
    [self updateClassInfo];

}

-(void)updateClassInfo{
    NSUserDefaults *defaults = [[NSUserDefaults alloc]initWithSuiteName:@"group.ZhangZhang.TodayExtensionSharingDefaults"];
    if ([defaults boolForKey:@"logged"] != YES) {
        self.preferredContentSize = CGSizeMake(320, 65);
        self.classView.hidden = YES;
        [self.view viewWithTag:92].hidden = YES;
        [self.view viewWithTag:97].hidden = NO;
        
        UILabel *label = (UILabel *)[[self.view viewWithTag:97] viewWithTag:98];
        label.text = @"请进入App并登录,查看当日课程";
    }else{
    NSArray *classArray = [defaults objectForKey:@"ClassesArray"];
    weekCount = [self getWeekCount];
    weekday = [self getWeekday];
    NSLog(@"at first weekcount is %d , weekdayis %d, count is %d classArray is %d",weekCount,weekday,self.displayArray.count,classArray.count);
    [self.displayArray removeAllObjects];
    for (NSDictionary *classes in classArray) {
        
        if ([classes[@"xingQi"] intValue] == weekday &&[self suitThisWeek:(NSDictionary *)classes]) {
            if ([classes[@"specialMark"] intValue] ==0) {
                [self.displayArray addObject:classes];
            }else if ([classes[@"specialMark"] intValue] ==1 && weekCount%2 == 0){
                [self.displayArray addObject:classes];
            }else if ([classes[@"specialMark"] intValue] ==2 && weekCount%2 == 1){
                [self.displayArray addObject:classes];
            }
        }
    }
    if (self.displayArray.count==0) {
        self.preferredContentSize = CGSizeMake(320, 65);
        self.classView.hidden = YES;
        [self.view viewWithTag:92].hidden = YES;
        [self.view viewWithTag:97].hidden = NO;
        UILabel *label = (UILabel *)[[self.view viewWithTag:97] viewWithTag:98];
        label.text = @"今日无课";
    }else{
        self.preferredContentSize = CGSizeMake(320, 65*self.displayArray.count);
        self.classView.hidden = NO;
        [self.view viewWithTag:92].hidden = NO;
        [self.view viewWithTag:97].hidden = YES;
    }
        NSArray *resultArray = [self.displayArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
            
            NSString *time1 = obj1[@"shiJian"];
            NSString *time2 = obj2[@"shiJian"];
            
            NSComparisonResult result = [time1 compare:time2];
            
            return result == NSOrderedDescending; // 升序
        }];
    
        self.displayArray = [resultArray mutableCopy];
    [self setupViews];
    }
}

-(void)setupViews{
    int i = 0;
    for (NSDictionary *classInfo in self.displayArray) {
        if (i==0) {
            [self setView:self.classView withShiJian:classInfo[@"shiJian"]];
            UILabel *nameOfClass = (UILabel *)[self.classView viewWithTag:3];
            UILabel *roomOfClass = (UILabel *)[self.classView viewWithTag:4];

            nameOfClass.text = classInfo[@"mingCheng"];
            roomOfClass.text = classInfo[@"jiaoShi"];
            NSLog(@"0time is %@",classInfo[@"shiJian"]);
        }
        
        else{
            UIView *classView = [self.view viewWithTag:i+91];
            NSLog(@"1ioutputis %d",i);
            [self setView:classView withShiJian:classInfo[@"shiJian"]];
            UILabel *nameOfClass = (UILabel *)[classView viewWithTag:3];
            UILabel *roomOfClass = (UILabel *)[classView viewWithTag:4];
            nameOfClass.text = classInfo[@"mingCheng"];
            roomOfClass.text = classInfo[@"jiaoShi"];
        }

        i++;
    }
    
}

-(void)setView:(UIView *)view withShiJian:(NSString *)shiJian{
    UILabel *timeStart = (UILabel *)[view viewWithTag:5];
    UILabel *timeEnd = (UILabel *)[view viewWithTag:6];
    if ([shiJian isEqualToString:@"1"]) {
        timeStart.text = @"8:00";
        timeEnd.text = @"9:35";
    }else if ([shiJian isEqualToString:@"2"]){
        timeStart.text = @"9:55";
        timeEnd.text = @"11:30";
    }else if ([shiJian isEqualToString:@"3"]){
        timeStart.text = @"13:30";
        timeEnd.text = @"15:05";
    }else if ([shiJian isEqualToString:@"4"]){
        timeStart.text = @"15:25";
        timeEnd.text = @"17:00";
    }else if ([shiJian isEqualToString:@"5"]){
        timeStart.text = @"18:00";
        timeEnd.text = @"19:35";
    }else if ([shiJian isEqualToString:@"6"]){
        timeStart.text = @"19:55";
        timeEnd.text = @"21:30";
    }
    
}
-(BOOL)suitThisWeek:(NSDictionary *)classes{
    int kaiShiZhou = [classes[@"kaiShiZhou"] intValue];
    int jieShuZhou = [classes[@"jieShuZhou"] intValue];
    if (kaiShiZhou <= weekCount && weekCount <= jieShuZhou) {
        return YES;
    }else{
        return NO;
    }

}


- (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
    // Perform any setup necessary in order to update the view.
    
    // If an error is encountered, use NCUpdateResultFailed
    // If there's no update required, use NCUpdateResultNoData
    // If there's an update, use NCUpdateResultNewData

    completionHandler(NCUpdateResultNewData);
}

@end
